<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <div>
            <input type="text" id="name">
            <button id="login">登录</button>
        </div>
        <input type="text" id="text">
        <button id="send">发送</button>
        <button id="quit">退出</button>
        <div class="box"></div>
    </div>
    <script>
        
        let send = document.querySelector('#send');

        let text = document.querySelector('#text');

        let name = document.querySelector('#name');

        let login = document.querySelector('#login');

        let box = document.querySelector('.box');


        let ws = new WebSocket('ws://localhost:8001');

        let quit = document.querySelector('#quit');

        ws.onopen = function(){
            console.log("链接建立成功");

            //登录
            login.addEventListener('click',() => {
                if(!name.value){
                    alert('用户名不存在')
                }else{
                    ws.send(JSON.stringify({
                        type:'login',
                        info:name.value
                    }))
                }
                login.setAttribute('disabled',true);
            })

            send.addEventListener('click',() => {
                if(!text.value){
                    alert("输入框为空")
                }else{
                    ws.send(JSON.stringify({
                        type:'chart',
                        info:text.value
                    }));
                }
            })

            quit.addEventListener('click',() => {
                ws.close();
            })
        }

        
        ws.onmessage = function(data){
            console.log(data)
            data = JSON.parse(data.data);
             let div = document.createElement('div');
            if(data.type === 'server'){
                div.innerHTML = `${data.info}加入了聊天室`;
            }else if(data.type === 'chart'){
                div.innerHTML = `${data.name}:${data.info}`;
            }else{
                div.innerHTML = `${data.name}退出了聊天室`;
            }
           
            box.appendChild(div);
        }
    </script>
</body>
</html>